 package com.oanda.blackberry.view;
 
 import com.oanda.blackberry.net.RestException;
 import com.oanda.blackberry.ui.BitmapButtonField;
 import com.oanda.blackberry.ui.ColoredCheckboxField;
 import com.oanda.blackberry.ui.OandaMainScreen;
 import com.oanda.blackberry.ui.SpacerField;
 import com.oanda.blackberry.ui.SpacerManager;
 import com.oanda.blackberry.util.AbstractViewPanel;
 import com.oanda.blackberry.util.DefaultController;
 import com.oanda.blackberry.util.PropertyChangeEvent;
 import com.oanda.blackberry.util.log.Logger;
 import net.rim.device.api.system.Bitmap;
 import net.rim.device.api.ui.Field;
 import net.rim.device.api.ui.FieldChangeListener;
 import net.rim.device.api.ui.Graphics;
 import net.rim.device.api.ui.Manager;
 import net.rim.device.api.ui.MenuItem;
 import net.rim.device.api.ui.Screen;
 import net.rim.device.api.ui.component.BasicEditField;
 import net.rim.device.api.ui.component.BitmapField;
 import net.rim.device.api.ui.component.CheckboxField;
 import net.rim.device.api.ui.component.EmailAddressEditField;
 import net.rim.device.api.ui.component.Menu;
 import net.rim.device.api.ui.component.PasswordEditField;
 import net.rim.device.api.ui.component.SeparatorField;
 import net.rim.device.api.ui.component.TextField;
 import net.rim.device.api.ui.container.HorizontalFieldManager;
 import net.rim.device.api.ui.container.MainScreen;
 import net.rim.device.api.ui.decor.Background;
 import net.rim.device.api.ui.decor.BackgroundFactory;
 import net.rim.device.api.ui.text.EmailAddressTextFilter;
 
 public class RegistrationView extends OandaMainScreen
   implements AbstractViewPanel
 {
   DefaultController controller;
   BasicEditField userName;
   PasswordEditField password;
   BasicEditField email;
   static final String ERROR_PASSWORD_MUST_BE_8_CHARACTERS = "Password must be at least 8 characters";
   static final String ERROR_USERNAME_MUST_BE_2_TO_50_CHARS = "Username length must be between 2 and 50 characters";
   static final String ERROR_USERNAME_MUST_BE_LETTERS_AND_DIGITS = "Username must be letters and digits";
   static final String ERROR_EMAIL_CANNOT_BE_EMPTY = "Email cannot be empty";
   static final String ERROR_EMAIL_MUST_BE_50_CHARS = "Email must be less than 50 characters long";
   static final String ERROR_INVALID_EMAIL_ENTERED = "Invalid Email entered";
   static final String TITILE_VALIDATION_ERROR = "Validation Error";
   static final String ERROR_USERNAME_IN_USE = "The username you selected is already in use";
   static final String ERROR_ERROR_WITH_YOUR_REGISTRATION = "There was an error with your registration, please try again";
   ColoredCheckboxField emailOptIn = new ColoredCheckboxField(14540253, "Yes, please email occasional OANDA newsletters, updates & promotions to me.", true, 8589934592L);
   BitmapButtonField submit;
   MenuItem submitMenu = new MenuItem("Submit", 10, 1000)
   {
     public void run() {
       RegistrationView.this.register();
     }
   };
 
   MenuItem back = new MenuItem("Back", 10, 1001)
   {
     public void run() {
       RegistrationView.this.onClose();
     }
   };
 
   public RegistrationView(DefaultController controller)
   {
     this.controller = controller;
     init();
   }
 
   public void modelPropertyChange(PropertyChangeEvent evt) {
     if ((evt.getPropertyName() != null) && (evt.getPropertyName().equals("setErrorMessage")))
     {
       if ((evt.getNewValue() != null) && ((evt.getNewValue() instanceof String))) {
         String statusText = (String)evt.getNewValue();
         diplayError(statusText, 3000);
       }
     }
     else if ((evt.getPropertyName() != null) && (evt.getPropertyName().equals("RegistrationException"))) {
       if ((evt.getNewValue() != null) && ((evt.getNewValue() instanceof RestException))) {
         RestException ex = (RestException)evt.getNewValue();
         if ((ex != null) && (ex.getErrorMessage().toLowerCase().indexOf("10: invalid account") > -1))
         {
           diplayError("The username you selected is already in use", 5000);
         }
         else diplayError("There was an error with your registration, please try again", 5000);
       }
     }
     else if ((evt.getPropertyName() != null) && (evt.getPropertyName().equals("setRegistrationStatus"))) {
       Logger.log("RegistrationView setRegistrationStatus: " + (String)evt.getNewValue());
       if ((evt.getNewValue() != null) && ((evt.getNewValue() instanceof String))) {
         String statusText = (String)evt.getNewValue();
         if ((statusText != null) && (statusText.length() > 0)) {
           setStatusField(statusText);
         }
         else {
           setStatusField("");
           removeStatusField();
         }
       }
 
     }
     else if ((evt.getPropertyName() != null) && (evt.getPropertyName().equals("showRegistration"))) {
       if (!isDisplayed())
       {
         this.controller.pushScreen(this);
       }
     } else if ((evt.getPropertyName() != null) && (evt.getPropertyName().equals("hideRegistration"))) {
       this.controller.popScreen(this);
     } else if ((evt != null) && (evt.getPropertyName().equals("showThrobber"))) {
       showThrobber();
     } else if ((evt != null) && (evt.getPropertyName().equals("hideThrobber"))) {
       hideThrobber();
     }
   }
 
   protected void makeMenu(Menu menu, int instance) {
     menu.add(this.submitMenu);
     menu.add(this.back);
   }
 
   private void init() {
     getTitleManager().deleteAll();
 
     getMainManager().setBackground(BackgroundFactory.createSolidBackground(4473924));
 
     createBackground();
     initFields();
 
     setFonts();
     setFieldsBg();
   }
 
   private void setFonts() {
   }
 
   private void setFieldsBg() {
     Background solidBackground = BackgroundFactory.createLinearGradientBackground(16777215, 14540253, 16777215, 14540253);
 
     Background greyBg = BackgroundFactory.createSolidBackground(OandaMainScreen.BG_COLOR);
     setBackground(greyBg);
 
     Bitmap header = Bitmap.getBitmapResource("header-480x97.png");
     BitmapField headerBitmapField = new BitmapField(header);
     add(headerBitmapField);
 
     getMainManager().setBackground(greyBg);
     this.userName.setBackground(solidBackground);
     this.password.setBackground(solidBackground);
     this.email.setBackground(solidBackground);
 
     add(new SeparatorField());
 
     add(new SpacerField(300, 10));
 
     HorizontalFieldManager row1 = new HorizontalFieldManager(1152921504606846976L);
     row1.add(new SpacerField(30, 1));
     SpacerManager usernameSpacerManager = new SpacerManager(193, 50);
     usernameSpacerManager.add(this.userName);
     row1.add(usernameSpacerManager);
     row1.add(new SpacerField(20, 1));
     add(row1);
 
     add(new SpacerField(300, 10));
 
     HorizontalFieldManager row2 = new HorizontalFieldManager(1152921504606846976L);
     row2.add(new SpacerField(30, 1));
     SpacerManager passwordSpacerManager = new SpacerManager(193, 50);
     passwordSpacerManager.add(this.password);
     row2.add(passwordSpacerManager);
     row2.add(new SpacerField(20, 1));
     add(row2);
 
     add(new SpacerField(300, 10));
 
     HorizontalFieldManager row3 = new HorizontalFieldManager(1152921504606846976L);
     row3.add(new SpacerField(30, 1));
     SpacerManager emailSpacerManager = new SpacerManager(193, 50);
     emailSpacerManager.add(this.email);
     row3.add(emailSpacerManager);
     row3.add(new SpacerField(20, 1));
 
     add(row3);
 
     add(new SpacerField(300, 10));
 
     HorizontalFieldManager row4 = new HorizontalFieldManager(1152921504606846976L);
     row4.add(new SpacerField(30, 1));
     row4.add(this.emailOptIn);
 
     add(row4);
 
     add(new SeparatorField());
 
     HorizontalFieldManager row5 = new HorizontalFieldManager(1152921504606846976L);
 
     row5.add(new SpacerField(30, 1));
     row5.add(this.submit);
     add(row5);
 
     this.submit.setChangeListener(new FieldChangeListener()
     {
       public void fieldChanged(Field field, int context) {
         if (RegistrationView.this.isValidForm())
           RegistrationView.this.register();
       }
     });
   }
 
   private boolean isValidForm() {
     boolean isValid = true;
 
     String errorMessage = "";
     String txtPassword = this.password.getText().trim();
     String txtUsername = this.userName.getText().trim();
     String txtEmail = this.email.getText().trim();
 
     if (txtPassword.equals("PASSWORD")) {
       txtPassword = "";
     }
     if (txtUsername.equals("USERNAME")) {
       txtUsername = "";
     }
     if (txtEmail.equals("EMAIL")) {
       txtEmail = "";
     }
 
     if (txtPassword.length() < 8) {
       isValid = false;
       errorMessage = "Password must be at least 8 characters";
     }
 
     int usernameLength = txtUsername.length();
     if ((usernameLength < 2) || (usernameLength > 50)) {
       isValid = false;
       errorMessage = "Username length must be between 2 and 50 characters";
     }
     else if (!isValidUsername(txtUsername)) {
       isValid = false;
       errorMessage = "Username must be letters and digits";
     }
 
     if (txtEmail.length() == 0) {
       isValid = false;
       errorMessage = "Email cannot be empty";
     }
     else if (txtEmail.length() > 50) {
       isValid = false;
       errorMessage = "Email must be less than 50 characters long";
     }
     else if (!isValidEmail(txtEmail)) {
       isValid = false;
       errorMessage = "Invalid Email entered";
     }
 
     if (!isValid)
     {
       diplayError(errorMessage, 5000);
     }
 
     return isValid;
   }
 
   private boolean isValidUsername(String userText)
   {
     if (Character.isDigit(userText.charAt(0))) {
       return false;
     }
     for (int index = 1; index < userText.length(); index++) {
       if (!isAlphaNum(userText.charAt(index))) {
         return false;
       }
     }
     return true;
   }
 
   private boolean isAlphaNum(char ch) {
     if (('0' <= ch) && (ch <= '9')) return true;
     if (('a' <= ch) && (ch <= 'z')) return true;
     return ('A' <= ch) && (ch <= 'Z');
   }
 
   private boolean isValidEmail(String passwordText)
   {
     int indexOfAt = passwordText.indexOf('@', 1);
     if (indexOfAt == -1) return false;
 
     int indexOfDot = passwordText.indexOf('.', indexOfAt + 1);
     if (indexOfDot == -1) return false;
 
     return indexOfDot != passwordText.length() - 1;
   }
 
   private void createBackground()
   {
   }
 
   private void initFields()
   {
     this.userName = new BasicEditField("", "USERNAME", 40, 2147483648L)
     {
       public boolean isFocusable() {
         return true;
       }
 
       protected void onFocus(int direction) {
         if (getText().equals("USERNAME"))
           setText("");
         invalidate();
         super.onFocus(direction);
       }
 
       protected void onUnfocus() {
         if (getText().equals(""))
           setText("USERNAME");
         invalidate();
         super.onUnfocus();
       }
 
       public void paint(Graphics g) {
         g.setColor(3355443);
         super.paint(g);
       }
     };
     this.password = new PasswordEditField("", "PASSWORD", 40, 2147483648L)
     {
       public boolean isFocusable() {
         return true;
       }
 
       protected void onFocus(int direction) {
         if (getText().equals("PASSWORD"))
           setText("");
         invalidate();
         super.onFocus(direction);
       }
 
       protected void onUnfocus() {
         if (getText().equals(""))
           setText("PASSWORD");
         invalidate();
         super.onUnfocus();
       }
       public void paint(Graphics g) {
         g.setColor(3355443);
         super.paint(g);
       }
     };
     this.email = new EmailAddressEditField("", "EMAIL", 40, 2147483648L)
     {
       public boolean isFocusable() {
         return true;
       }
 
       protected void onFocus(int direction) {
         if (getText().equals("EMAIL"))
           setText("");
         invalidate();
         super.onFocus(direction);
       }
 
       protected void onUnfocus() {
         if (getText().equals(""))
           setText("EMAIL");
         invalidate();
         super.onUnfocus();
       }
 
       public void paint(Graphics g) {
         g.setColor(3355443);
         super.paint(g);
       }
     };
     this.email.setFilter(new EmailAddressTextFilter());
 
     this.submit = new BitmapButtonField(Bitmap.getBitmapResource("submit-button-hover.png"), Bitmap.getBitmapResource("submit-button-p8.png"), "Submit", 12884967424L);
   }
 
   private void register()
   {
     this.controller.submitRegistration(this.userName.getText(), this.password.getText(), this.email.getText(), this.emailOptIn.getChecked());
   }
 
   public boolean onClose()
   {
     this.controller.popScreen(this);
     return true;
   }
}

